﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;

namespace P2PChat.Client.UI
{
    /// <summary>
    /// WinFriendSearch_Page_InputInfo.xaml 的交互逻辑
    /// </summary>
    public partial class WinFriendSearch_Page_InputInfo : Page
    {
        public WinFriendSearch_Page_InputInfo()
        {
            InitializeComponent();
        }

        private void btn_Search_Click(object sender, RoutedEventArgs e)
        {
            if (txt_Nickname.Text.Trim() == "" && txt_Email.Text.Trim() == "")
            {
                MessageBox.Show("请最少输入一个信息");
            }
            else
            {
                System.Threading.Thread thread_DoSearch = new System.Threading.Thread(threadMain_DoSearch);
                thread_DoSearch.Start();
            }
        }

        private WinFriendSearch_Page_ShowResult pg_ShowResult = new WinFriendSearch_Page_ShowResult();

        private void threadMain_DoSearch()
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                this.txt_Email.IsEnabled = false;
                this.txt_Nickname.IsEnabled = false;
                this.btn_Search.IsEnabled = false;
            }));

            // 获取输入的信息
            string inputNickname = null, inputEmail = null;
            this.Dispatcher.Invoke(new Action(() =>
            {
                if (txt_Nickname.Text.Trim() != "") inputNickname = txt_Nickname.Text;
                if (txt_Email.Text.Trim() != "") inputEmail = txt_Email.Text;
            }));

            

            // 创建网络包
            P2PChat.Data.NetPacket packet = new P2PChat.Data.NetPacket()
            {
                Tag = P2PChat.Data.PacketTag.SearchFriend,
                Content = new P2PChat.Data.Packets.SearchFriendPacket()
                {
                    SearchText_Nickname = inputNickname,
                    SearchText_Email = inputEmail,
                },
            };

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            bf.Serialize(ms, packet);

            using (System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient())
            {
                try
                {
                    // 发送数据包
                    client.Connect(GlobalConfig.ServerHost, GlobalConfig.ServerPort);
                    client.Client.Send(ms.GetBuffer());

                    // 接收回发包并反序列化
                    P2PChat.Data.NetPacket recvPacket =
                        bf.Deserialize(client.GetStream()) as P2PChat.Data.NetPacket;
                    if (recvPacket.Tag == P2PChat.Data.PacketTag.ServerException)
                    {
                        throw new Exception("服务器处理过程中出现了异常!");
                    }
                    XElement list = (recvPacket.Content as P2PChat.Data.Packets.SearchFriendResultPacket).ResultXml;
                    if (list.HasElements)
                    {
                        this.Dispatcher.Invoke(new Action(() => { pg_ShowResult.ui_ResultList.Items.Clear(); }));
                        foreach (XElement person in list.Elements("PersonalInfo"))
                        {
                            this.Dispatcher.Invoke(new Action(() =>
                            {
                                ListBoxItem nwItem = new ListBoxItem();
                                pg_ShowResult.ui_ResultList.Items.Add(nwItem);
                                nwItem.Content = string.Format(
                                    @"昵称:{0} 电子邮件地址:{1}", 
                                    person.Element("Nickname").Value, 
                                    person.Attribute("RegEmail").Value);
                                this.NavigationService.Navigate(pg_ShowResult);
                            }));
                        }
                    }
                    else
                    {
                        MessageBox.Show("服务器未返回任何结果!");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("检测到异常:" + ex.Message);
                }

                this.Dispatcher.Invoke(new Action(() =>
                {
                    this.txt_Email.IsEnabled = true;
                    this.txt_Nickname.IsEnabled = true;
                    this.btn_Search.IsEnabled = true;
                }));
            }
            
        }
    }
}
